<template>
	<div style="height:200vh;min-width: 1200px;" class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto layout-padding-view">
			<div class="system-user-search mb15">
                <el-button @click="toUsermanege()">返回</el-button>
			</div>
            <div class="formPart">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formDataList"
        :inline="true"
        label-width="200px"
        class="demo-formData"
      >
        <el-form-item  label="头像：" prop="avatar" style="width: 100%;height:230px">
            <div class="author_line">
                <el-upload
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    @change="change"
                    :on-success="hanldleSuccess"
                >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <!-- <div style="height:50px;width:176px;display:flex;justify-content:space-between;padding-bottom:10px">
                    <el-link type="success" @click="uploadSuccess">上传</el-link>
                    <el-link type="danger" @click="closeUpload">取消上传</el-link>
                </div> -->
            </div>
        </el-form-item>
        <el-form-item label="用户账号：" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            type="password"
            v-model="formData.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号码：" prop="mobile">
          <el-input v-model="formData.mobile"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱：" prop="email">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="enabled">
          <el-switch v-model="formData.enabled"></el-switch>
        </el-form-item>
        <el-form-item label="角色：" style="width: 100%">
          <el-transfer
            v-model="formData.roles"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入搜索内容"
            :titles="['未授权权限', '已授权权限']"
            :props="{
              key: 'id',
              label: 'label',
            }"
            :data="rolesData"
          ></el-transfer>
        </el-form-item>
        <el-form-item class="butt" >
          <div style="min-width: 300px;">
            <el-button type="primary" @click="addUser" v-if="!gid">创建</el-button>
            <el-button type="primary" @click="EditUser" v-if="gid">保存</el-button>
            <el-button @click="toResize">重置</el-button>
          </div>
          
        </el-form-item>
      </el-form>
    </div>
		</div>
	</div>
</template>

<script lang="ts" setup>
	import {ref,reactive,onMounted} from "vue"
    import { useRouter,useRoute } from 'vue-router';
    import { updateApi } from "/@/api/upload/index";
    import {usermanegeApi} from "/@/api/system/usermanege/index"
    import {rolesApi} from "/@/api/system/roles/index"
    import { ElMessage } from "element-plus";
    import { systemStore } from "/@/stores/system";
    const syStore = systemStore()
    const manegeApi = usermanegeApi()
    const updatedApi = updateApi()
    const roleApi = rolesApi()
    let imageUrl = ref<any>("") //上传图片的路径
    const fileObj = ref({
        file:null,
        type:'image',
        path:""
    }) //上传图片的文件包
    const rolesData = ref([])
    const formData:any =ref({
        avatar_url: "",
        username: "",
        password: "",
        name: "",
        mobile: "",
        email: "",
        enabled: false,
        roles: [],
        created_at: "",
        updated_at: "",
        pay_password: "",
    })
    const gid:any = ref(null)
    const formDataList:any =ref(null)
    const router= useRouter()
    const route = useRoute()
    const toUsermanege = ()=>{
        router.go(-1)
    }
    let rules = ref({
         username: [
          { required: true, message: "请输入用户账号", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
        enabled: [{ required: true, message: "请选择状态", trigger: "blur" }],
        email: {
          type: "email",
          required: true,
          message: "请输入正确的邮箱地址",
          trigger: "blur",
        },
    })
    let change = (async(uploadFile:any)=>{
        imageUrl.value= URL.createObjectURL(uploadFile.raw)
        fileObj.value.file = uploadFile.raw
        let headers = {
        "Content-Type": "multipart/form-data"
      }
        if(fileObj.value.file){
            const res = await updatedApi.isUpdate(headers,fileObj.value)
            if(res.isSuccess){
              formData.value.avatar_url = res.returnData.path
            }
        }else{
            ElMessage.error("请先选择您要上传的文件")
        }
    })
    const hanldleSuccess=()=>{
      
    }
    // 添加用户
    const addUser = (async()=>{
        let data = formData.value
        let res = await manegeApi.createUser(data);
        if(res.isSuccess){
          ElMessage.success('添加成功')
          formDataList.value.resetFields()
          router.go(-1)
        }
    })
    const filterMethod = (query:any, item:any)=> {
     
      return item.label.indexOf(query) > -1;
    }

    // 获取权限列表
    const getRolesList = (async ()=>{
        let res = await roleApi.getRolesList({});
        if(res.isSuccess){
          rolesData.value = res.returnData
        }
    })
    const resizeData = ref([])
    // const resizeObj = {}
    // 编辑跳转过来的回显
    const echoData = ( async () =>{
        if(gid.value){
          let res = await manegeApi.getUserDetail({id:gid.value,include:'roles'});
          if(res.isSuccess){
            formData.value = res.returnData
            syStore.userObj =res.returnData
            resizeData.value = res.returnData 
            formData.value.enabled = formData.value.enabled==1?true:false
            formData.value.password =  "__NO_CHANGE__"
            if (formData.value.pay_password != "") {
              formData.value.pay_password =  "__NO_CHANGE__"
            }
            imageUrl.value = formData.value.avatar_url
            formData.value.roles =formData.value.roles.map((item:any) => {
                return item.id;
            });
          }
        }
    })
    // 重置
    const toResize = ()=>{
      if(!gid.value){
        formDataList.value.resetFields()
      }else{
        echoData()
      }
    }
    // 编辑用户
    const EditUser = (async ()=>{
      let data = formData.value;
      data.id = gid.value
      let res =await manegeApi.updateUser(data);
      if(res.isSuccess){
        ElMessage.success('编辑成功')
        
        // formDataList.value.resetFields()
        router.go(-1)
      }
    })

    onMounted(()=>{
      // 获取路由里传递的参数
      gid.value = route.query.id
     
      getRolesList()
      echoData()
    })
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;
		.el-table {
			flex: 1;
		}
	}
}
.system-user-search{
    padding:20px 0 ;
    border-bottom:1px solid #dcdfe6;
}
.leftpart{
	font-size: 18px;
}
.system-user-content{
	height: 60px;
	line-height: 60px;
	display: flex;
	justify-content: space-between;
}
.el-input{
	height: 40px;
}
.el-button{
	height: 40px;
}
.formPart {
    width: 95%;
    margin: 0 auto;
    .el-form-item {
      margin: 20px 0;
      width: 50%;
      ::v-deep .el-form-item__content {
        width: 70% !important;
      }
    }

    .el-input {
      width: 350px;
      width: 100%;
    }
    .butt {
      width: 100%;
      margin: 20px auto;
      text-align: center;
      padding: 0 45%;
    }
  }
::v-deep .el-transfer-panel {
  width: 350px;
}
::v-deep
  .el-transfer-panel
  .el-transfer-panel__header
  .el-checkbox
  .el-checkbox__label {
  font-size: 14px !important;
}
::v-deep .el-transfer-panel__body {
  height: 330px;
}
::v-deep .el-transfer-panel__list.is-filterable {
  height: 275px;
  // padding-top: 0;
}
::v-deep .el-transfer {
  .el-transfer__buttons {
    .el-button {
      padding: 10px;
    }
  }
}
.author_line{
    width: 178px;
    height: 178px;
    border: 1px dashed #ccc;
}  
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.avatar-uploader .el-upload {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}
  
.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
} 
</style>